use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

async fn handle_client(mut stream: tokio::net::TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).await.unwrap();
    
    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; // 模拟耗时操作
    let response = b"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello Async!";
    stream.write_all(response).await.unwrap();
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = TcpListener::bind("127.0.0.1:7880").await?;
    println!("异步服务器监听在 127.0.0.1:7880");
    
    loop {
        let (stream, _) = listener.accept().await?;
        tokio::spawn(async move {
            handle_client(stream).await;
        });
    }
}
